<?php

namespace App\Http\Controllers\Api;

use App\Http\Helpers\Api\ApiResponse;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    use ApiResponse;

    /**
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request){
        $token = auth()->attempt(['account'=>$request->account,'password'=>$request->password]);
        if($token) {
            return $this->setStatusCode(201)->success(['token' => 'bearer ' . $token]);
        }
        return $this->failed('账号或密码错误',400);
    }

    /**
     * @return mixed
     */
    public function loginOut(){
        auth()->logout();
        return $this->success('退出成功...');
    }


    /**
     * 返回当前登录用户信息
     * @param Request $request
     * @return mixed
     */
    public function info(Request $request){

        $user = $request->user();
        return $this->success($user);
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function register(Request $request)
    {
        $member = [
            'nickname'=>$request->nickname,
            'account' => $request->account,
            'password' => Hash::make($request->password),
        ];
        User::create($member);
        return $this->setStatusCode(201)->success('用户注册成功');
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function changePw(Request $request)
    {
        $user = $request->user();
        $user->update(['password' => $request->password]);
        $token = auth()->refresh();
        return $this->setStatusCode(201)->setToken($token)->success('修改密码成功');
    }



}
